

def convert_operation_format(current_operation):
    """
    将单个工序数据从旧格式转换为新格式
    
    Args:
        current_operation: 单个工序的完整数据（旧格式）
        
    Returns:
        dict: 转换后的工序数据（新格式）
    """
    # 新建一个空字典，用于存储转换后的工序信息
    converted_operation = {}
    
    # 设置必须的字段
    converted_operation['number'] = current_operation['工序节点']['properties'].get('mpm_id', '')
    
    # 从current_operation中获取工序名称
    if '工序节点' in current_operation and 'properties' in current_operation['工序节点']:
        converted_operation['name'] = current_operation['工序节点']['properties'].get('工序名称', '未知工序')
    else:
        converted_operation['name'] = '未知工序'
    
    # 设置默认的固定值
    converted_operation['type'] = "OperationIteration"
    converted_operation['modelDefinition'] = "MachiningOperation"
    
    # 初始化children列表
    converted_operation['children'] = []
    
    # 添加工步信息（从工步列表中获取）
    if '工步列表' in current_operation:
        for step_idx, step_info in enumerate(current_operation['工步列表'], 1):
            if '工步节点' in step_info and 'properties' in step_info['工步节点']:
                step_properties = step_info['工步节点']['properties']
                # 初始化工步数据
                step_data = {
                    "number": step_properties.get('mpm_id',''),
                    "name": step_properties.get('工步名称', f'工步{step_idx}'),
                    "type": "Sequence",
                    "modelDefinition": "Sequence",
                    "description": step_properties.get('工步内容及加工要求', ''),
                    "children": []  # 初始化为空列表，后续动态添加资源
                }
                
                # 从step_info中获取设备、制造资源和辅料信息
                # 处理设备信息 - type:ResourceIteration, modelDefinition:Equipment
                if '设备列表' in step_info and isinstance(step_info['设备列表'], list):
                    for idx, equipment in enumerate(step_info['设备列表'], 1):
                        if isinstance(equipment, dict):
                            equipment_item = {
                                "number": equipment['properties'].get('mpm_id',''),
                                "name": equipment['properties']['设备名称'],
                                "type": equipment['properties'].get('mpm_type',''), 
                                "modelDefinition": equipment['properties'].get('mpm_modelDefinition',''),
                                "quantity": equipment['properties'].get('数量', ''),
                                "unit": equipment['properties'].get('单位', '')
                            }
                            step_data['children'].append(equipment_item)
                
                # 处理制造资源信息 - type:ResourceIteration, modelDefinition:MeasuringInstrument
                if '制造资源列表' in step_info and isinstance(step_info['制造资源列表'], list):
                    for idx, resource in enumerate(step_info['制造资源列表'], 1):
                        if isinstance(resource, dict):
                            resource_item = {
                                "number": resource['properties'].get('mpm_id',''),
                                "name": resource['properties']['资源名称'],
                                "type": resource['properties'].get('mpm_type',''), 
                                "modelDefinition": resource['properties'].get('mpm_modelDefinition',''),
                                "quantity": resource['properties'].get('数量', ''),
                                "unit": resource['properties'].get('单位', '')
                            }
                            step_data['children'].append(resource_item)
                
                # 处理辅料信息 - type:PartIteration, modelDefinition:Accessories
                if '辅料列表' in step_info and isinstance(step_info['辅料列表'], list):
                    for idx, material in enumerate(step_info['辅料列表'], 1):
                        if isinstance(material, dict):
                            material_item = {
                                "number": material['properties'].get('mpm_id',''),
                                "name": material['properties']['辅料名称'],
                                "type": material['properties'].get('mpm_type',''), 
                                "modelDefinition": material['properties'].get('mpm_modelDefinition',''),
                                "quantity": material['properties'].get('数量', ''),
                                "unit": material['properties'].get('单位', '')
                            }
                            step_data['children'].append(material_item)
                
                # 保持children为空列表，不添加任何默认资源
                
                # 添加工步检列表作为inspectionInfoItems
                if '工步检列表' in step_info:
                    step_data['inspectionInfoItems'] = []
                    for inspect_idx, inspect_info in enumerate(step_info['工步检列表'], 1):
                        if 'properties' in inspect_info:
                            inspect_properties = inspect_info['properties']
                            inspect_item = {
                                "orderNo": inspect_idx,
                                "name": inspect_properties.get('记录项检验项名称', f'检验项{inspect_idx}'),
                                "checkClass": inspect_properties.get('分类名称', '未知分类'),
                                "unit": inspect_properties.get('计量单位', ''),
                                "checkFace": inspect_properties.get('检测面', ''),
                                "technicalIndex": inspect_properties.get('设计值技术指标', ''),
                                "type": "InspectionInfoItem",
                                "modelDefinition": "InspectionSequenceItem",
                                # 再加上 检测角度 注释 检测光波长 检测口径通光口径 说明 备注
                                "checkAngle": inspect_properties.get('检测角度', ''),
                                "explanNote": inspect_properties.get('注释', ''),
                                "checkOpticalLenght": inspect_properties.get('检测光波长', ''),
                                "checkCaliber": inspect_properties.get('检测口径通光口径', ''),
                                "description": inspect_properties.get('说明', ''),
                                "remark": inspect_properties.get('备注', ''),
                            }
                            step_data['inspectionInfoItems'].append(inspect_item)
                
                converted_operation['children'].append(step_data)
    
    # 添加工序检列表作为inspectionInfoItems
    if '工序检列表' in current_operation:
        converted_operation['inspectionInfoItems'] = []
        for inspect_idx, inspect_info in enumerate(current_operation['工序检列表'], 1):
            if 'properties' in inspect_info:
                inspect_properties = inspect_info['properties']
                inspect_item = {
                    "orderNo": inspect_idx,
                    "name": inspect_properties.get('检验项目名称', f'工序检验项{inspect_idx}'),
                    "checkClass": inspect_properties.get('分类名称', '未知分类'),
                    "unit": inspect_properties.get('计量单位',''),
                    "checkFace": inspect_properties.get('检测面', ''),
                    "technicalIndex": inspect_properties.get('设计值技术指标', ''),
                    "type": "InspectionInfoItem",
                    "modelDefinition": "InspectionOperationItem",
                    # 再加上 检测角度 注释 检测光波长 检测口径通光口径 说明 备注
                    "checkAngle": inspect_properties.get('检测角度', ''),
                    "explanNote": inspect_properties.get('注释', ''),
                    "checkOpticalLenght": inspect_properties.get('检测光波长', ''),
                    "checkCaliber": inspect_properties.get('检测口径通光口径', ''),
                    "description": inspect_properties.get('说明', ''),
                    "remark": inspect_properties.get('备注', ''),
                }
                converted_operation['inspectionInfoItems'].append(inspect_item)
    
    # 添加优化建议（固定文本）
    converted_operation['optimization_reason'] = "无！！！！！"
    
    return converted_operation



import pandas as pd
from typing import Dict, Any, List

def convert_drawing_format_to_dataframe(drawing_data: List[Dict[str, Any]]) -> pd.DataFrame:
    """
    将新的图纸数据格式直接转换为DataFrame
    保留所有有用的元数据信息
    
    参数:
        drawing_data: 新的图纸数据格式
        
    返回:
        pandas.DataFrame: 包含所有检测信息的DataFrame
    """
    data_records = []
    
    for category_item in drawing_data:
        for category_name, inspection_items in category_item.items():
            # 遍历每个检测项
            for item in inspection_items:
                if isinstance(item, dict):
                    record = {
                        "check_class": item.get("checkClass", ""),  # 检测分类
                        "name": item.get("name", ""),  # 检测名称
                        "check_face": item.get("checkFace", ""),  # 检测面
                        "technical_index": item.get("technicalIndex", ""),  # 技术指标
                        "unit": item.get("unit", ""),  # 单位
                        "check_angle": item.get("checkAngle", ""),  # 检测角度
                        "check_caliber": item.get("checkCaliber", ""),  # 检测口径
                        "check_optical_length": item.get("checkOpticalLenght", ""),  # 检测光程
                        "description": item.get("description", "")  # 描述
                    }
                    data_records.append(record)
    
    # 创建DataFrame
    df = pd.DataFrame(data_records)
    
    # 确保必要的列存在
    required_columns = ["check_class", "name", "check_face", "technical_index"]
    for col in required_columns:
        if col not in df.columns:
            df[col] = ""
    
    return df





def fix_drawing_surfaces(drawing_data: Dict[str, Dict[str, Any]]) -> pd.DataFrame:
    """
    将图纸信息数据转换为包含检测面分类的DataFrame
    
    参数:
        drawing_data: 图纸信息数据字典
        
    返回:
        pandas.DataFrame: 转换后的图纸信息数据表格，包含"检验项目名称"、"检测面"、"原始分类"、"设计值技术指标"列
    """
    # 如果未提供数据，则使用默认的接口入参数据
    if drawing_data is None:
        raise ValueError("未提供数据")
    
    # 需要特殊处理的类别，为它们添加平面和非球面两种检测面
    special_categories = {"表面质量", "面形PSD-2", "表面粗糙度Rq"}
    
    data_list = []
    for category, params in drawing_data.items():
        for param, value in params.items():
            if category in special_categories:
                # 为特殊类别添加平面和非球面两种检测面
                data_list.append({
                    "原始分类": category,
                    "检测面": "平面",
                    "检验项目名称": param,
                    "设计值技术指标": value
                })
                data_list.append({
                    "原始分类": category,
                    "检测面": "非球面",
                    "检验项目名称": param,
                    "设计值技术指标": value
                })
            else:
                # 普通类别不区分检测面
                data_list.append({
                    "原始分类": category,
                    "检测面": "",
                    "检验项目名称": param,
                    "设计值技术指标": value
                })
    
    # 创建并返回DataFrame
    return pd.DataFrame(data_list)






if __name__ == "__main__":
    
    from temp.入参接口 import 图纸入参接口
    drawing_data = 图纸入参接口
    df = fix_drawing_surfaces(drawing_data)
    
    # 显示结果
    print("转换后的图纸信息数据:")
    print(f"数据行数: {len(df)}")
    print("列名:", df.columns.tolist())

    # 保存到文件
    df.to_csv("output.csv", index=False)
